package logic

import (
	"MyBlogv2/blog-common/helper"
	"MyBlogv2/blog-common/models"
	"context"
	"github.com/jinzhu/copier"

	"MyBlogv2/Servers/Article/article"
	"MyBlogv2/Servers/Article/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetArticleListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetArticleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetArticleListLogic {
	return &GetArticleListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetArticleListLogic) GetArticleList(in *Article.ArticleRequest) (*Article.GetArticleListResponse, error) {
	var articleVoList []models.ArticleListVo
	models.Db.Model(new(models.ArticleListVo)).
		Table("t_article a").
		Select("a.*,c.category_name as category_name,u.username as username").
		Joins("left join t_category c on a.category_id = c.id").
		Joins("left join sys_user u on a.user_id = u.id").
		Find(&articleVoList)

	for i, v := range articleVoList {
		var tagsName []string
		models.Db.Model(new(models.ArticleTag)).
			Distinct("t.tag_name").
			Table("t_article_tag at").
			Select("t.tag_name").
			Joins("left join t_tag t on at.tag_id = t.id").
			Where("at.article_id = ?", v.Id).
			Find(&tagsName)
		articleVoList[i].TagsName = tagsName
	}
	var articleListVoResponse []*Article.ArticleListVo
	copier.Copy(&articleListVoResponse, &articleVoList)
	for i, v := range articleVoList {
		articleListVoResponse[i].CreateTime = helper.MyTimeToTimestamp(v.CreateTime)
	}

	return &Article.GetArticleListResponse{
		Code: 200,
		Data: articleListVoResponse,
	}, nil
}
